package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/exercicio02")
public class Exercico02 extends HttpServlet {
	private List<String> recados;

	public Exercico02() {
		super();
		recados = new ArrayList<String>();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		criarFormulario(req, resp);
		mostrarRecados(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		criarFormulario(req, resp);
		mostrarRecados(req, resp);
	}

	private void mostrarRecados(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String nome = req.getParameter("nome");
		String recado = req.getParameter("recado");
		PrintWriter out = resp.getWriter();
		if (nome != null && recado != null) {
			if (!nome.trim().equals("") && !recado.trim().equals("")) {
				recados.add(nome + " <i> escreveu: </i> " + recado +"</br>");
			}
		}
		// montar a saida dos recados

		out.println("<h1> Recados</h1>");
		if (recados != null && recados.size() > 0){
			for(String s:recados){
				out.println(s);
			}
		}
		out.println("</body>");
		out.println("</html>");
	}

	private void criarFormulario(HttpServletRequest req,
			HttpServletResponse resp) throws IOException {
		resp.setContentType("text/html");
		PrintWriter out = resp.getWriter();
		out.println("<html><head><title>Exercicio 02</title></head>");
		out.println("<body>");
		out.println("<form action=\"exercicio02\" method=\"post\">");
		out.println("Nome:</br>");
		out.println("<input type=\"text\" name=\"nome\"/></br>");
		out.println("Recado:</br>");
		out.println("<textarea name=\"recado\" rows=\"4\" cols=\"50\" ></textarea></br>");
		out.println("<input type=\"submit\" value=\"Enviar\"/>");
		out.println("</form>");
	}
}
